package cn.kgc.login.service;

import cn.kgc.common.entity.Author;
import cn.kgc.login.dao.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by teacher ZHANG on 2022/12/5
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private RedisDao redisDao;

    @Override
    public void saveAuthor(String token, Author author) {
        Map<String, String> map = new HashMap<>();
        map.put("authorId", (author.getAuthorId().toString()));
        map.put("username", author.getUsername());
        map.put("nickname", author.getNickname());
        map.put("realName", author.getRealName());
        map.put("phone", author.getPhone());

        redisDao.hashSet(token, map); //保存用户信息
        redisDao.setExpire(token, 1800); //过期时间为半小时
    }

    @Override
    public Author findAuthor(String token) {
        Map<Object, Object> map = redisDao.hashGet(token);
        if (map == null) {
            return null;
        }

        Author author = new Author();
        author.setAuthorId(Integer.parseInt((String) map.get("authorId")));
        author.setUsername((String) map.get("username"));
        author.setNickname((String) map.get("nickname"));
        author.setRealName((String) map.get("realName"));
        author.setPhone((String) map.get("phone"));

        return author;
    }

    @Override
    public Boolean tokenExist(String token) {
        return redisDao.keyExist(token);
    }

    @Override
    public Integer getExpire(String key) {
        return redisDao.getExpire(key);
    }

    @Override
    public void setExpire(String key, Integer secs) {
        redisDao.setExpire(key, secs);
    }

    @Override
    public void savePhone(String phone, String code) {
        redisDao.strSet(phone, code, 60);
    }

    @Override
    public String getPhone(String phone) {
        return redisDao.strGet(phone);
    }
}
